﻿using UnityEngine;
using System.Collections;

/// <summary>
/// 挂在有标准BoxCollider（旋转为0）或SphereCollider（椭圆形无效）的物体上
/// 当target（默认为玩家）进入范围时，函数isPlayerInRange()返回true，否则返回false
/// </summary>
public class PlayerInRange : MonoBehaviour {
	public enum RangeType{
		NOTHING,
		SPHERE,
		BOX
	};
	public RangeType rangeType;
	public float minDis = 3f;
	///默认为玩家
	[SerializeField] GameObject target;
	public bool isPlayerInRange() {
		if (target == null) {
			target = StaticVarFunc.Player;
		}
		switch (rangeType) {
		case RangeType.BOX:
			BoxCollider boxCol = GetComponent<BoxCollider> ();
			if (boxCol != null) {
				Vector3 dis3 = target.transform.position - transform.position;
				///必须注意localscale的大小
				if (Mathf.Abs (dis3.x) < boxCol.size.x/2f && Mathf.Abs (dis3.y) < boxCol.size.y/2f && Mathf.Abs (dis3.z) < boxCol.size.z/2f) {
					return true;
				} else {
					return false;
				}
			}
			break;
		case RangeType.SPHERE:
			SphereCollider sphCol = GetComponent<SphereCollider> ();
			if (sphCol != null) {
				float dis = (target.transform.position - transform.position).magnitude;
				if (dis < sphCol.radius * transform.localScale.x) {
					return true;
				} else {
					return false;
				}
			}
			break;
		case RangeType.NOTHING:
			float dis = (target.transform.position - transform.position).magnitude;
			if (dis < minDis)
				return true;
			else
				return false;
			break;
		default:
			break;
		}
		return false;
	}
}
